/**
 * Created by chocolate on 16/4/30.
 */
import React, {
    Component,
    StyleSheet,
    Text,
    TextInput,
    View,
    TouchableOpacity,
    TabBarIOS,
    Image,
    ListView,
    SegmentedControlIOS,
    ActivityIndicatorIOS,
    Alert,
    Modal,
    Dimensions,
} from 'react-native';


var query = require('./Query').query;
var Title = require('./Title');
var SegmentedView =require('react-native-segmented-view');

//将来这个数据在componentDidMount的时候,从服务器里面获取
var EventListTest = [{time:"2016-05-10 13:30:00",type:1},
    {time:"2016-05-10 11:30:00",type:0},
    {time:"2016-05-10 08:30:00",type:1},
    {time:"2016-05-10 13:30:00",type:1},
    {time:"2016-05-10 11:30:00",type:0},
    {time:"2016-05-10 08:30:00",type:1},
]

var thresh_hold_hours = 1;
var morning_enter_time = "09:00:00";
var evening_leave_time = "18:30:00";

var statusStrArray = ['过早入校','正常入校','迟到','早退','正常离校','过晚离校','未按时入校','未按时离校'];



class DiEvents extends Component{
    constructor(props){
        super(props);
        this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.eventList = [];                                //从服务器获取的event列表
        this.state = {
            isLoading:true,                                //是否正在加载数据
            selectedTab:'baobao',                           //TabBar的默认选项页
            selectedIndex:0,                                //SegmentedControlIOS的默认选项页
            parent:this.props.parent,                         //当前家长对象(从login模块传递过来的)
            childNames: ['王小刚', '王小丽', '王小聪'],        //SegmentedControlIOS的数据源(来源于child列表)
            dataSource:this.ds.cloneWithRows(EventListTest),  //ListView的数据源
            selectedRowData:null,
            modalVisible: false,
            redBubble:false,
        }
    }

    componentWillUnmount() {
        //结束时必须清空定时器，否则它会一直在运行
        this.timer && clearTimeout(this.timer);
  }

    componentWillMount(){
        //childList必定是从父级传递
        var childNameList = [];
        this.props.childList.forEach((item, index, array) =>{
            childNameList.push(item.name);
        })
        this.setState({childNames:childNameList});

        this.timer = setInterval(()=>{
                    this.setState({redBubble:!(this.state.redBubble)});
                },1000)
    }

    /**
     * 根据家长电话号码到服务器查找其关联的所有学生,
     * 用户名称(电话)是由login模块传递过来
     */
    componentDidMount(){
        this._fetchEvents();
    }

    /**
     * 处理事件列表，分析出状态编码，状态字符串，以及告警，
     * 并将这些信息插入到事件列表中，用于后续的界面渲染
     */
    _processEventList(){
        if(this.eventList.length === 0){
            return;
        }
        this.eventList.forEach((item, index, array)=>{
            item.forEach((item, index, array)=>{
                var code=this._parseSchoolStatus(item.type,item.time);
                item.status_code = code;
                item.status_str = statusStrArray[code];
                item.alarm = (code != 1 && code != 4)?true:false;
            })
        })
    }

    /**
     * 根据出入类型和出入事件分析抱抱事件
     * 返回学生状态编码(入校和出现门限时间从服务器中获取)
     */
    _parseSchoolStatus(eventType,eventTime){

        enterDate = new Date();
        enterDate.setHours(9);
        enterDate.setMinutes(0);
        enterDate.setSeconds(0);

        enterThreshDate = new Date();
        enterThreshDate.setHours(9-1);
        enterThreshDate.setMinutes(0);
        enterThreshDate.setSeconds(0);

        leaveDate = new Date();
        leaveDate.setHours(18);
        leaveDate.setMinutes(0);
        leaveDate.setSeconds(0);

        leaveThreshDate = new Date();
        leaveThreshDate.setHours(18+1);
        leaveThreshDate.setMinutes(0);
        leaveThreshDate.setSeconds(0);

        // var year = Number(eventTime.substring(0,4));
        // var month = Number(eventTime.substring(5,7))-1;
        // var day = Number(eventTime.substring(8,10));
        // var hour = Number(eventTime.substring(11,13));
        // var minute = Number(eventTime.substring(14,16));
        // var second = Number(eventTime.substring(17,19));
        // eventDate = new Date(year,month,day,hour,minute,second);
        eventDate = Date.FromString(eventTime);

        var code ;
        if(eventType === 0)
        {
            if(eventDate < enterThreshDate)
            {
                code = 0;   //过早入校
            }
            else if(eventDate > enterThreshDate && eventDate < enterDate)
            {
                code = 1; // 按时入校
            }
            else if(eventDate > enterDate)
            {
                code = 2;  //迟到入校
            }
        }
        else if(eventType === 1)
        {
            if(eventDate < leaveDate)
            {
                code = 3;   //早退离校
            }
            else if(eventDate > leaveDate && eventDate < leaveThreshDate)
            {
                code = 4;   //正常离校
            }
            else if(eventDate > leaveThreshDate)
            {
                code = 5;   //过晚离校
            }
        }
        else if(eventType === 2)
        {
            code = 6;  //未按时入校
        }
        else if(eventType === 3)
        {
            code = 7;  //未按时离校
        }
        return code;
    }

    /**
     *从服务器获取当日的事件列表,
     * 并更新相关视图
     * @private
     */
    _fetchEvents(){
        this.eventList = [];
        //var date = "2016-06-06";
        var date = new Date().Format('yyyy-MM-dd');
        this.setState({isLoading:true});

        this.props.childList.forEach((item, index, array) =>{
            console.log("get " + item.name + "'s event");
            query.getEventQuery(item.bbId,date,this,function(owner,response){
                if(response.success === true){
                    owner.eventList[index] = response.message;
                    console.log(owner.eventList);
                    owner._processEventList();
                    owner._updateListView();}})})
    }

    /**
     * 使用eventlist更新当前页面的ListView
     * @private
     */
    _updateListView(){
        var eventList = (this.state.selectedIndex >= this.eventList.length)?[]:this.eventList[this.state.selectedIndex];
        this.setState({dataSource:this.ds.cloneWithRows(eventList)});
        this.setState({isLoading:false});
    }


    /**
     * 家长进入主界面后,可以没有绑定学生。点击此按钮可以进入绑定视图,s
     * 与注册时看到的绑定视图是一样的
     */
    _onBinding(){
        this.props.navigator.push({name:'Bind',params:{phone:this.state.parent.phone,onChildChange:this.props.onChildChange}});
    }

    /**
    * 点击SegmentBar更换学生
    */
    _onPressSegment(index){
        this.setState({selectedIndex: index});
        this._updateListView();
    }

    /**
    * 点击事件列表，弹出告警详情
    */
    _onPressEventBar(rowData){
        this.setState({selectedRowData:rowData});
        this._setModalVisible(true);
    }

    /**
    * 返回告警详情，用于modal显示
    */
    _getDetailAlarm(){
        if(this.state.selectedRowData === null)
        {
            return;
        }
        var enter_or_leave = (this.state.selectedRowData.type === 0) ? '入校':'离校';
        var leave_reason = (this.state.selectedRowData.type === 1) && (<Text style={styles.detailContent}>离校原因:不详</Text>);
        return(
                <View>
                    <Text style={styles.detailContent}>学生姓名：{this.state.childNames[this.state.selectedIndex]}</Text>
                    <Text style={styles.detailContent}>学生状态：{this.state.selectedRowData.status_str}</Text>
                    <Text style={styles.detailContent}>{enter_or_leave}时间：{this.state.selectedRowData.time}</Text>
                    {leave_reason}
                    <Text style={styles.detailContent}>立即联系班主任：13800000000</Text>
                </View>
            )
    }

    /**
     * 渲染孩子事件列表的每一行数据
     * @param rowData
     * @param sectionID
     * @param rowID
     * @returns {XML}
     */
    renderEventRecord(rowData: string,sectionID: number, rowID: number){
        //在抱抱界面看到的是当天的事件数据,因此不需要日期,只需要时间
        var time = rowData.time.substring(11,19);

        return (
            <View style={styles.row}>
                <View style={styles.timeline}/>
                <Image style={styles.bubblestate} source={(rowData.alarm === true) 
                                        ? require('../../icon/timeline-alarm.png')
                                        : require('../../icon/timeline-check.png')}/> 

                <TouchableOpacity style={{alignItems:'center'}} onPress={()=>{this._onPressEventBar(rowData)}}>
                    <Image style={styles.bubble} source={(rowID === '0' && rowData.alarm === true && this.state.redBubble === true) 
                                ? require('../../icon/bubble-red.png') 
                                : require('../../icon/bubble.png')}>
                        <Text style={styles.bubbleText}>{time}</Text>
                        <Text style={styles.bubbleText}>{rowData.status_str}</Text>
                    </Image>
                </TouchableOpacity>
            </View>)
    }

    _setModalVisible(visible) {
        this.setState({modalVisible: visible});
    }

    renderProcessor(){
        return(
            <View style={{flex:1,backgroundColor:'#2981b1',alignItems:'center',justifyContent:'center'}}>
                <ActivityIndicatorIOS
                    hidden='true'
                    size='large'/> 
                <Text style={{color:'#fff'}}>正在努力加载中...</Text>
            </View>
        )
    }

    renderMain(){
        //childList必定是从父级传递
        var childNameList = [];
        this.props.childList.forEach((item, index, array) =>{
            childNameList.push(item.name);
        })
        return(
             <View style={styles.container}>
                <Modal
                    animated={true}
                    transparent={true}
                    visible={this.state.modalVisible}
                    onRequestClose={() => {this._setModalVisible(false)}}>
                    <View ref = 'outterContainer'
                        onStartShouldSetResponderCapture={(e) => {
            　　　　　　　　const target = e.nativeEvent.target;
                          console.log("点击事件被触发,target:"+target);
                          console.log("outterContainer's target:"+React.findNodeHandle(this.refs.outterContainer));
                          console.log("innerContainer's target:"+React.findNodeHandle(this.refs.innerContainer));
                          console.log("confirmButton's target:"+React.findNodeHandle(this.refs.confirmButton));
            　　　　　　　　if (target === React.findNodeHandle(this.refs.outterContainer)) {
            　　　　　　　　　　this._setModalVisible(false);
                             console.log("关闭modal");
            　　　　　　　　}
                        }}
                        style={styles.modalContainer}>
                        <View ref='innerContainer' onStartShouldSetResponderCapture={(e) => {
                            const target = e.nativeEvent.target;
                            console.log("modalContainer:点击事件被触发,target:"+target);
                        }}
                            style={styles.detailContainer}>
                            <Text style={styles.detailTitle}>告警详情</Text>
                            
                            {this._getDetailAlarm()}

                            <View style={styles.detaiButtonContainer}>
                                <TouchableOpacity ref='confirmButton' style={styles.detailButton}
                                    onPress={this._setModalVisible.bind(this, false)}>
                                    <Text style={styles.detailButtonText}>确认</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                </Modal>

                <Title title={{center:"抱抱",left:"刷新",leftAct:this._fetchEvents.bind(this),
                        right:"绑定",rightAct:this._onBinding.bind(this)}}></Title>

                 <SegmentedView
                    titles={childNameList}
                    index={this.state.selectedIndex}
                    stretch={true}
                    barPosition={'bottom'}
                    onPress={this._onPressSegment.bind(this)}
                    style={{flex:0}}/>

                <View style = {styles.ItemContainer}>
                    <Image style={styles.Picture}
                        source={require('../../icon/in-school.png')}
                    />
                    <ListView dataSource={this.state.dataSource}
                              renderRow={this.renderEventRecord.bind(this)}
                              enableEmptySections={true}
                              style={styles.listView} />
                </View>
                    
            </View>
        );
    }

    render(){

        var display = this.state.isLoading ?(this.renderProcessor()):( this.renderMain());

        return(
            <View style={styles.container}>
                {display}
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#eeeeee',
        flex: 1,
    },
    Title: {
        height: 40,
        marginTop: 20,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        borderColor: 'gray',
        borderTopWidth: 1,
        borderBottomWidth: 1,
    },
    ItemContainer:{
        flexDirection:'column',
        alignItems:'center',
        flex:1
    },
    Picture:{
        alignSelf:'center',
        height:230,
    },
    listView: {
        marginLeft:170,
        marginRight:170,
        paddingTop: 5,

    },
    row:{
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems:'center',

    },
    text:{
        textAlign:'center',
        fontSize:10,
        backgroundColor:'rgba(254,254,254,0)',
    },
    timeline:{
        width:1,
        alignSelf:'stretch',
        borderStyle:'solid',
        borderWidth:1,
        borderColor:'#d4d4d4',
        marginLeft:30,
    }, 
    bubble:{
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'space-between',
        paddingLeft:30,
        paddingRight:30,
        marginTop:25,
        marginLeft:5,
    },
    bubblestate:{
        marginLeft:-10,
        marginTop:20,
    },
    bubbleText:{
        color:'#a7a7a7',
        fontSize:20,
        backgroundColor:'#FFF'
    },
    modalContainer:{
        flex: 1,
        backgroundColor:'rgba(0, 0, 0, 0.5)',
        justifyContent:'center',
    },
    detailContainer:{
        marginLeft:40,
        marginRight:40,
        backgroundColor:'#FFF',
        justifyContent:'center',
        borderWidth:1,
        borderStyle:'solid',
        borderColor:'#2981b1',
        borderRadius:12,
    },
    detailTitle:{
        marginTop:20,
        marginBottom:20,
        alignSelf:'center',
        color:'#161616',
        fontSize:20,
    },
    detailContent:{
        marginLeft:15,
        marginBottom:15,
        color:'#555454',
        fontSize:16,
    },
    detaiButtonContainer:{
        flexDirection:'row',
        alignItems:'center',
        borderTopWidth:1,
        borderStyle:'solid',
        borderColor:'#2981b1',
    },
    detailButton:{
        flex:1,
        height:40,
        marginBottom:5,
        alignItems:'center',
        justifyContent:'center',
    },
    detailButtonText:{
        fontSize:20,
        color:'#06a9fe',
    }
})

module.exports = DiEvents;